#include "mymath.h"

MyMath::MyMath()
{

}

//Floating-point data is converted to character type data
void MyMath::FloatTo4Bytes(float f_temp, char *chr)
{
    union FloatToChar
    {
        float temp;
        char chr[4];
    };
    FloatToChar ftc;
    ftc.temp = f_temp;
    for (int i = 0; i < 4;i++)
        chr[i] = ftc.chr[i];
}

//Character type data is converted to Floating-point data
float MyMath::FourBytesToFloat(char *chr)
{
    float f;
    union CharToFloat
    {
        float temp;
        char chr[4];
    };
    CharToFloat ctf;
    for (int i = 0; i < 4; i++)
        ctf.chr[i] = chr[i];
    f= ctf.temp;
    return f;
}

float MyMath::FourBytesToFloat(QByteArray datas)
{
    char chr[4]={0};
    for(int i=0;i<4;i++)
        chr[i]=datas.at(i);
    float f;
    union CharToFloat
    {
        float temp;
        char chr[4];
    };
    CharToFloat ctf;
    for (int i = 0; i < 4; i++)
        ctf.chr[i] = chr[i];
    f= ctf.temp;
    return f;
}

float MyMath::StringToFloat(QByteArray str)
{
    int StrLength=str.length();//长度
    int RedixPointAt=0;//确定小数点位置
    bool isPositive;//是否为正数
    int INT=0;
    float FLOAT=0;
    if(str.at(0)=='-')
        isPositive=false;
    else
        isPositive=true;
    for(int i=1;i<StrLength;i++)
    {
        if(str.at(i)=='.')//检查小数点的位置
        {
            RedixPointAt=i;
            break;
        }
    }
    if(isPositive){
        for(int i=0;i<RedixPointAt;i++)
        {
            INT=INT+(str.at(i)-48)*qPow(10,RedixPointAt-i-1);
        }
    }
else{
        for(int i=1;i<RedixPointAt;i++)
        {
            INT=INT+(str.at(i)-48)*qPow(10,RedixPointAt-i-1);
        }
    }
    for(int i=RedixPointAt+1;i<StrLength;i++)
    {
        FLOAT=FLOAT+((float)(str.at(i)-48))/qPow(10,i-RedixPointAt);
    }
    if(isPositive)
        return INT+FLOAT;
    else
        return -(INT+FLOAT);
}

char MyMath::CRC8_32(char *chr)
{
    char CRC=0x00;
    for(int j=0;j<4;j++){
        CRC^=*chr++;
        for(int i=0;i<4;i++){
            if(CRC&0x80){
                CRC=(CRC<<1)^0x31;
            }
            else
                CRC=CRC<<1;
        }
    }
    return CRC;
}

char MyMath::CRC8_8(char chr)
{
    char CRC=chr;
    for(int i=0;i<8;i++){
        if(CRC&0x80){       //判断最高位是否为1
            CRC=(CRC<<1)^0x31;
        }
        else
            CRC=CRC<<1;
    }
    return CRC;
}

char MyMath::CRC8Table_32(char *chr)
{
    char CRC=0x00;
    for(int i=0;i<4;i++){
        CRC=CRC8Table[CRC^*chr++];
    }
    return CRC;
}

